#!/bin/bash
#********************************************************************
#Name:          test
#Date:          2024-08-26
#FileName：     init_mysql5.sh
#Description:   The test script
#********************************************************************

echo "安装mysql===============================================" 

#创建用户
id mysql &>/dev/null
if [ $? -eq 0 ];then
    echo "用户存在"
else
    useradd -M -r -s /sbin/nologin/ mysql
fi
echo -e "\033[31m 用户创建完成 \033[0m"

#解压软件包
tar -xvf mysql-5.7.44-linux-glibc2.12-x86_64.tar.gz -C /usr/local/ &>/dev/null
cd /usr/local/
ln -s mysql-5.7.44-linux-glibc2.12-x86_64 mysql
chown -R mysql.mysql /usr/local/mysql
echo -e "\033[31m 安装包解压完成 \033[0m"

#配置环境变量
echo 'PATH=$PATH:/usr/local/mysql/bin' > /etc/profile.d/mysql.sh
source /etc/profile.d/mysql.sh
echo -e "\033[31m 环境变量配置完成 \033[0m"

#创建数据存放目录
mkdir /opt/data
chown -R mysql.mysql /opt/data/
echo -e "\033[31m 目录创建完成 \033[0m"
#初始化数据库
/usr/local/mysql/bin/mysqld --initialize-insecure --user=mysql --datadir=/opt/data/ &>/dev/null
echo -e "\033[31m 初始化数据库 \033[0m"
#修改配置文件
cat > /etc/my.cnf <<EOF
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve
EOF
cd /usr/local/mysql/support-files/
cp -a mysql.server /etc/init.d/mysqld
echo -e "\033[31m 配置完成 \033[0m"

#配置systemd启动服务
cat > /usr/lib/systemd/system/mysqld.service <<EOF
[Unit]
Description=mysqld server daemon
After=network.target sshd-keygen.target

[Service]
Type=forking
ExecStart=/etc/init.d/mysqld  start
ExecStop=/etc/init.d/mysqld  stop
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl start mysqld.service
echo "启动服务"
if [ $? -eq 0 ];then
  echo "mysql服务启动成功"
else 
  echo "服务启动失败"
fi
#修改密码
read -p "输入设置的数据库密码：" passwd
mysql -uroot -e "set password = password('"$passwd"')"
echo -e "\033[31m 修改密码完成 \033[0m"
echo 'source /etc/profile.d/mysql.sh' 复制粘贴运行




